package com.musicserver.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.musicserver.common.R;
import com.musicserver.model.domain.RankList;
import com.musicserver.model.request.RankListRequest;
import com.musicserver.service.RankListService;
import com.musicserver.mapper.RankListMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
* @author tch001
* @description 针对表【rank_list】的数据库操作Service实现
* @createDate 2025-09-25 15:59:21
*/
@Service
public class RankListServiceImpl extends ServiceImpl<RankListMapper, RankList>
    implements RankListService{

    @Autowired
    private RankListMapper rankListMapper;

    @Override
    public R addRank(RankListRequest rankListAddRequest) {
        RankList rankList = new RankList();
        BeanUtils.copyProperties(rankListAddRequest, rankList);
        if (rankListMapper.insert(rankList) > 0)
            return R.success("提交评分成功");
        else
            return R.error("提交评分失败");
    }

    @Override
    public R rankOfSongListId(Long songListId) {
        // 评分总人数如果为 0，则返回0；否则返回计算出的结果
        QueryWrapper<RankList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("song_list_id",songListId);
        /** 获取评分总人数 */
        Long rankNum = rankListMapper.selectCount(queryWrapper);
        /** 如果评分总人数大于0，则查询歌单评分总和并处以总人数得出该歌单评分 */
        return R.success("查询评分成功",
                (rankNum <= 0) ? 0 : rankListMapper.selectScoreSum(songListId) / rankNum);
    }

    @Override
    public R rankOfUserId(long consumerId, long songListId) {
        QueryWrapper<RankList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("consumer_id",consumerId).eq("song_list_id",songListId);
        RankList rankList = rankListMapper.selectOne(queryWrapper);
        if (rankList != null)
            return R.success("查询评分成功",rankList.getScore());
        else
            return R.success("查询评分成功",null);
    }
}




